package com.study.java8.functioninterface;


import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

public class Excercise {
    public static void main(String[] args){

        Excercise excercise = new Excercise();
        Function<Integer, String> func = x -> "Result: " + x;
        BiFunction<Integer, Integer, Integer> biFunc = (x, y) -> x * y;

        // 链式函数
        String result = biFunc.andThen(func).apply(2, 4);
        System.out.println(result);

        // BinaryOperator
        BinaryOperator<Integer>  binaryOperator = (x, y) -> x * y;
        System.out.println(binaryOperator.apply(3, 2));

        // UnaryOperator
        UnaryOperator<Integer> unaryOperator = x -> x * 5;
        System.out.println(unaryOperator.apply(5));

        // Predicate
        List preList = new ArrayList(){{add(1);add(2);add(3);}};
        Predicate<Integer> noGreaterThan2 = (x) -> x <= 2;
        List resList = (List) preList.stream().filter(noGreaterThan2).collect(Collectors.toList());

        // Consumer
        Consumer<String> print = x -> System.out.println(x);
        print.accept("tom");

        // group
        List<String> groupList = new ArrayList<String>(){{add("a");add("b");add("c");add("a");add("a");add("c");}};
        Map<String, Long> groupResult = groupList.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(groupResult);

        // group sort
        Map<String, Long> finalMap = new LinkedHashMap<>();
        groupResult.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).forEachOrdered(e -> {
            finalMap.put(e.getKey(), e.getValue());
        });
        System.out.println(finalMap);

    }


    public <T, R> List<R> map(List<T> list, Function<T, R>func){
        List<R>  result = new ArrayList<>();
        for(T t : list){
            result.add(func.apply(t));
        }
        return result;
    }
}
